<?php

namespace app\queue\redis;

use app\cms\model\Project;
use app\model\DownloadZip as AppDownloadZip;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use support\customHelpers;
use support\Log;
use support\PackZip;
use Webman\RedisQueue\Consumer;
use ZipArchive;

class DownloadZip implements Consumer
{
    // 要消费的队列名
    public $queue = 'download-zip';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        // 无需反序列化
        $project_id = $data['id'];
        // 清洗数据获取url
        $res = customHelpers::assembleUrlArray($data);
        // Log::info('文件下载地址' . json_encode($res));
        $downloadZipName = isset($data['project_name']) ? $data['project_name'] : 'project-download-zip';
        // 2. 下载七牛云的文件到本地并打包压缩
        // $zipFileName = PackZip::packFile(public_path(), $res, $downloadZipName);
        Log::info('开始打包压缩');
        $zipFileName = PackZip::packNetFile2Local($res, $downloadZipName['project_name']);

        if ($zipFileName) {
            if (!empty($project_id) && isset($project_id)) {
                Project::where('id', $project_id)->update([
                    'project_download_zip' => $zipFileName,
                ]);
                AppDownloadZip::where('project_id', $project_id)->update([
                    'status' => 1,
                ]);
            }
        }
    }

    // 消费成功回调
    public function onConsumeSuccess($package)
    {
        Log::info('下载打包压缩"consume success\n"; ');
    }

    // 消费失败回调
    /* 
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */


    public function onConsumeFailure(\Throwable $e, $package)
    {
        echo "consume failure\n";
        echo $e->getMessage() . "\n";
        // 无需反序列化
        var_export($package);
    }
}
